#!/bin/bash

CUR_PATH="$( cd "$( dirname $0 )" && pwd )"
CONF_FILE="${CUR_PATH}/nginx_log.conf"
LOG_PATH="${CUR_PATH}/logs"

function check_logpath() {
  if [ ! -d ${LOG_PATH} ]; then
    mkdir -p ${LOG_PATH}
  fi
  return 0
}

function log_info() {
  log "INFO:" $@
  return 0
}

function log() {
  echo "`date +'%Y-%m-%d %H:%M:%S'` $@" >> "${LOG_PATH}/`date +'%y%m%d'`.log"
  return 0
}

function main_split() {
  cat ${CONF_FILE} | while read svr_conf
  do
    local base_path=`echo ${svr_conf}|awk -F ',' '{print $1}'`
    local pidfile=`echo ${svr_conf}|awk -F ',' '{print $2}'`
    local logfile=`echo ${svr_conf}|awk -F ',' '{print $3}'`

    cut_single ${base_path} ${pidfile} ${logfile}
  done
  return 0
}

function cut_single() {
  local pidfile="$1/$2"
  local logfile="$1/$3"
  if [ -f ${pidfile} ] && [ -f ${logfile} ]; then
    local file_size=`stat -c "%s" ${logfile}`
    if [ ${file_size} -gt 1 ]; then
      backup_single ${logfile} && kill -USR1 `cat ${pidfile}` && log_info "cut_single success. [${logfile}]"
    else
      log_info "logfile size too small. [${logfile}]"
    fi
  else
    log_info "pidfile or logfile does not exists. $@"
  fi
  return 0
}

function backup_single() {
  local logfile=$1
  local logfile_bk="${logfile}.`date +'%y%m%d'`"
  local backup_cmd=""
  if [ -f ${logfile_bk} ]; then
    cat ${logfile} >> ${logfile_bk} && rm ${logfile} && log_info "cat ${logfile} >> ${logfile_bk} && rm ${logfile}"
  else
    mv ${logfile} ${logfile_bk} && log_info "mv ${logfile} ${logfile_bk}"
  fi
  return 0
}

check_logpath
main_split
